package solutions.leetcode.easy;

import java.util.Stack;

/**
 * @author lizhidong
 * <a href="https://leetcode-cn.com/problems/valid-parentheses/">20. 有效的括号</a>
 */
public class Solution20 {

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        int p = 0;
        while (p < s.length()) {
            char c = s.charAt(p++);
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else {
                Character top = stack.isEmpty() ? null : stack.pop();
                if (top == null) {
                    return false;
                }
                if (!((c == ')' && top == '(')
                        || (c == '}' && top == '{')
                        || (c == ']' && top == '['))
                ) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        Solution20 solution = new Solution20();
        System.out.println(solution.isValid("(()){}[]{(})}"));
    }
}